﻿layui.define(['layer', 'laytpl', 'form', 'element', 'upload', 'util', 'flow'], function (exports) {

    var $ = layui.jquery
        , layer = layui.layer
        , laytpl = layui.laytpl
        , form = layui.form
        , element = layui.element
        , upload = layui.upload
        , util = layui.util
        , device = layui.device()
        , flow = layui.flow
        , DISABLED = 'layui-btn-disabled';

    //阻止IE7以下访问
    if (device.ie && device.ie < 8) {
        layer.alert('如果您非得使用 IE 浏览器访问，那么请使用 IE8+');
    }

    layui.focusInsert = function (obj, str) {
        var result, val = obj.value;
        obj.focus();
        if (document.selection) { //ie
            result = document.selection.createRange();
            document.selection.empty();
            result.text = str;
        } else {
            result = [val.substring(0, obj.selectionStart), str, val.substr(obj.selectionEnd)];
            obj.focus();
            obj.value = result.join('');
        }
    };

    //数字前置补零
    layui.laytpl.digit = function (num, length, end) {
        var str = '';
        num = String(num);
        length = length || 2;
        for (var i = num.length; i < length; i++) {
            str += '0';
        }
        return num < Math.pow(10, length) ? str + (num | 0) : num;
    };

    var fly = {
        //Ajax
        json: function (url, data, success, options) {
            url = lucode.serverURL + url;

            var that = this, type = typeof data === 'function';
            // 获取当前 用户的 Uid,
            var userInfo=lucode.getUserInfo();
            console.log(userInfo);
            if (userInfo == false){
                return false;
            }
            data.userId = userInfo.userId;
            if (data.content != null) {
                data.content = /^\{html\}/.test(data.content)
                    ? data.content.replace(/^\{html\}/, '')
                    : fly.content(data.content);
            }

            if (type) {
                options = success;
                success = data;
                data = {};
            }

            options = options || {};
            //console.log(data);
            return $.ajax({
                type: options.type || 'post',
                dataType: options.dataType || 'json',
                data: data,
                url: url,
                success: function (res) {
                    if (res.resCode === lucode.SUCCESS) {
                        // 清空原先
                        success && success(res);
                    } else {
                        console.log(res);
                        layer.msg(res.msg || res.code, {shift: 6});
                        options.error && options.error();
                    }
                }, error: function (e) {
                    console.log("请求异常");
                    layer.msg('请求异常，请重试', {shift: 6});
                    options.error && options.error(e);
                }
            });
        }

        //计算字符长度
        , charLen: function (val) {
            var arr = val.split(''), len = 0;
            for (var i = 0; i < val.length; i++) {
                arr[i].charCodeAt(0) < 299 ? len++ : len += 2;
            }
            return len;
        }

        , form: {}

        //简易编辑器
        , layEditor: function (options) {
            var html = ['<div class="layui-unselect fly-edit">'
                , '<span type="face" title="插入表情"><i class="iconfont icon-yxj-expression" style="top: 1px;"></i></span>'
                , '<span type="picture" title="插入图片：img[src]"><i class="iconfont icon-tupian"></i></span>'
                , '<span type="href" title="超链接格式：a(href)[text]"><i class="iconfont icon-lianjie"></i></span>'
                , '<span type="code" title="插入代码或引用"><i class="iconfont icon-emwdaima" style="top: 1px;"></i></span>'
                , '<span type="hr" title="插入水平线">hr</span>'
                , '<span type="yulan" title="预览"><i class="iconfont icon-yulan1"></i></span>'
                , '</div>'].join('');

            var log = {}, mod = {
                face: function (editor, self) { //插入表情
                    var str = '', ul, face = fly.faces;
                    for (var key in face) {
                        str += '<li title="' + key + '"><img src="' + face[key] + '"></li>';
                    }
                    str = '<ul id="LAY-editface" class="layui-clear">' + str + '</ul>';
                    layer.tips(str, self, {
                        tips: 3
                        , time: 0
                        , skin: 'layui-edit-face'
                    });
                    $(document).on('click', function () {
                        layer.closeAll('tips');
                    });
                    $('#LAY-editface li').on('click', function () {
                        var title = $(this).attr('title') + ' ';
                        layui.focusInsert(editor[0], 'face' + title);
                    });
                }
                , picture: function (editor) { //插入图片
                    layer.open({
                        type: 1
                        , id: 'fly-jie-upload'
                        , title: '插入图片'
                        , area: 'auto'
                        , shade: false
                        , area: '465px'
                        , fixed: false
                        , offset: [
                            editor.offset().top - $(window).scrollTop() + 'px'
                            , editor.offset().left + 'px'
                        ]
                        , skin: 'layui-layer-border'
                        , content: ['<ul class="layui-form layui-form-pane" style="margin: 20px;">'
                            , '<li class="layui-form-item">'
                            , '<label class="layui-form-label">URL</label>'
                            , '<div class="layui-input-inline">'
                            , '<input required name="image" placeholder="支持直接粘贴远程图片地址" value="" class="layui-input">'
                            , '</div>'
                            , '<button type="button" class="layui-btn layui-btn-primary" id="uploadImg"><i class="layui-icon">&#xe67c;</i>上传图片</button>'
                            , '</li>'
                            , '<li class="layui-form-item" style="text-align: center;">'
                            , '<button type="button" lay-submit lay-filter="uploadImages" class="layui-btn">确认</button>'
                            , '</li>'
                            , '</ul>'].join('')
                        , success: function (layero, index) {
                            var image = layero.find('input[name="image"]');

                            //执行上传实例
                            upload.render({
                                elem: '#uploadImg'
                                , url: lucode.serverURL + '/file/upload/'
                                , data: {"uploadDir": "/cms/"}
                                , size: 2000
                                , done: function (res) {
                                    if (res.resCode == lucode.SUCCESS) {
                                        image.val(res.data);
                                        layui.focusInsert(editor[0], 'img[' + res.data + '] ');
                                        layer.msg("上传成功", {icon: 1});
                                        layer.close(index);

                                    } else {
                                        layer.msg(res.resMsg, {icon: 5});
                                    }
                                }
                            });

                            form.on('submit(uploadImages)', function (data) {

                                var field = data.field;
                                if (!field.image) return image.focus();
                                layui.focusInsert(editor[0], 'img[' + field.image + '] ');
                                layer.close(index);
                            });
                        }
                    });
                }
                , href: function (editor) { //超链接
                    layer.prompt({
                        title: '请输入合法链接'
                        , shade: false
                        , fixed: false
                        , id: 'LAY_flyedit_href'
                        , offset: [
                            editor.offset().top - $(window).scrollTop() + 'px'
                            , editor.offset().left + 'px'
                        ]
                    }, function (val, index, elem) {
                        if (!/^http(s*):\/\/[\S]/.test(val)) {
                            layer.tips('他么的！这根本不是个链接，不要骗我。', elem, {tips: 1});
                            return;
                        }
                        layui.focusInsert(editor[0], ' a(' + val + ')[' + val + '] ');
                        layer.close(index);
                    });
                }
                , code: function (editor) { //插入代码
                    layer.prompt({
                        title: '请贴入代码或任意文本'
                        , formType: 2
                        , maxlength: 10000
                        , shade: false
                        , id: 'LAY_flyedit_code'
                        , area: ['800px', '360px']
                    }, function (val, index, elem) {
                        layui.focusInsert(editor[0], '[pre]\n' + val + '\n[/pre]');
                        layer.close(index);
                    });
                }
                , hr: function (editor) { //插入水平分割线
                    layui.focusInsert(editor[0], '[hr]');
                }
                , yulan: function (editor) { //预览
                    var content = editor.val();

                    content = /^\{html\}/.test(content)
                        ? content.replace(/^\{html\}/, '')
                        : fly.content(content);

                    layer.open({
                        type: 1
                        , title: '预览'
                        , shade: false
                        , area: ['100%', '80%']
                        , scrollbar: false
                        , content: '<div class="detail-body" style="margin:20px;">' + content + '</div>'
                    });
                }
            };

            layui.use('face', function (face) {
                options = options || {};
                fly.faces = face;
                $(options.elem).each(function (index) {
                    var that = this, othis = $(that), parent = othis.parent();
                    parent.prepend(html);
                    parent.find('.fly-edit span').on('click', function (event) {
                        var type = $(this).attr('type');
                        mod[type].call(that, othis, this);
                        if (type === 'face') {
                            event.stopPropagation()
                        }
                    });
                });
            });

        }

        , escape: function (html) {
            return String(html || '').replace(/&(?!#?[a-zA-Z0-9]+;)/g, '&amp;')
                .replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/'/g, '&#39;').replace(/"/g, '&quot;');
        }

        //内容转义
        , content: function (content) {
            //支持的html标签
            var html = function (end) {
                return new RegExp('\\n*\\[' + (end || '') + '(pre|hr|div|span|p|table|thead|th|tbody|tr|td|ul|li|ol|li|dl|dt|dd|h2|h3|h4|h5)([\\s\\S]*?)\\]\\n*', 'g');
            };
            content = fly.escape(content || '') //XSS
                .replace(/img\[([^\s]+?)\]/g, function (img) {  //转义图片
                    return '<img src="' + img.replace(/(^img\[)|(\]$)/g, '') + '">';
                }).replace(/@(\S+)(\s+?|$)/g, '@<a href="javascript:;" class="fly-aite">$1</a>$2') //转义@
                .replace(/face\[([^\s\[\]]+?)\]/g, function (face) {  //转义表情
                    var alt = face.replace(/^face/g, '');
                    return '<img alt="' + alt + '" title="' + alt + '" src="' + fly.faces[alt] + '">';
                }).replace(/a\([\s\S]+?\)\[[\s\S]*?\]/g, function (str) { //转义链接
                    var href = (str.match(/a\(([\s\S]+?)\)\[/) || [])[1];
                    var text = (str.match(/\)\[([\s\S]*?)\]/) || [])[1];
                    if (!href) return str;
                    var rel = /^(http(s)*:\/\/)\b(?!(\w+\.)*(sentsin.com|layui.com))\b/.test(href.replace(/\s/g, ''));
                    return '<a href="' + href + '" target="_blank"' + (rel ? ' rel="nofollow"' : '') + '>' + (text || href) + '</a>';
                }).replace(html(), '\<$1 $2\>').replace(html('/'), '\</$1\>') //转移HTML代码
                .replace(/\n/g, '<br>'); //转义换行
            return content;
        }


    };
    //加载编辑器
    fly.layEditor({
        elem: '.fly-editor'
    });

    //表单提交
    form.on('submit(*)', function (data) {
        var action = $(data.form).attr('action'), button = $(data.elem);
        fly.json(action, data.field, function (res) {
            var end = function () {
                if (res.action) {
                    //console.log("请求成功")
                    //location.href = res.action;
                    //layer.msg("发布成功");

                } else {
                    fly.form[action || button.attr('key')](data.field, data.form);
                }
            };
            if (res.status == 0) {
                button.attr('alert') ? layer.alert(res.msg, {
                    icon: 1,
                    time: 10 * 1000,
                    end: end
                }) : end();
            }
        });
        return false;
    });


    //展开聊天系统
    $('body').on('click', '#LAY_signin', function () {
        layer.open({
            title:'聊天系统',
            type: 2,
            area: ['100%', '88%'],
            fixed: false, //不固定
            maxmin: true,
            moveOut: true,
            shade: 0,
            content: lucode.QiQiImURL+'/login'
        });
    });

    //回帖榜
    var tplReply = ['{{# layui.each(d.data, function(index, item){ }}'
        , '<dd>'
        , '<a href="/u/{{item.uid}}">'
        , '<img src="{{item.user.avatar}}">'
        , '<cite>{{item.user.username}}</cite>'
        , '<i>{{item["count(*)"]}}次回答</i>'
        , '</a>'
        , '</dd>'
        , '{{# }); }}'].join('')
        , elemReply = $('#LAY_replyRank');

    if (elemReply[0]) {
        /*
        fly.json('/top/reply/', {
          limit: 20
        }, function(res){
          var html = laytpl(tplReply).render(res);
          elemReply.find('dl').html(html);
        });
        */
    }

    //相册
    if ($(window).width() > 750) {
        layer.photos({
            photos: '.photos'
            , zIndex: 9999999999
            , anim: -1
        });
    } else {
        $('body').on('click', '.photos img', function () {
            window.open(this.src);
        });
    }

    //搜索
    $('.fly-search').on('click', function () {

        layer.open({
            type: 1
            , title: false
            , closeBtn: false
            , shadeClose: true
            , maxWidth: 10000
            , skin: 'fly-layer-search'
            , content: ['<input autocomplete="off" id="search" placeholder="搜索内容，回车跳转" type="text" name="q">'].join('')
            // , success: function (layero) {
            //     //<form action='+lucode.serverURL+'"/cmsPost/search">
            //     console.log("dasdasdasdasdasdadAS");
            //     return false;
            //     var input = layero.find('input');
            //     input.focus();
            //
            //     layero.find('form').submit(function () {
            //         var val = input.val();
            //         if (val.replace(/\s/g, '') === '') {
            //             return false;
            //         }
            //         console.log(input.val());
            //         input.val(input.val());
            //     });
            // }
        });



        // 监听 回车 事件
        $('#search').bind('keydown',function(event){
            if(event.keyCode == "13") {
                 layer.closeAll();

                layui.data('search', {
                    key: 'text'
                    ,value: $('#search').val()
                });
                lucode.openWindow(lucode.cms + "/case/case.html");
            }
        });




    });



    //加载特定模块
    if (layui.cache.page && layui.cache.page !== 'index') {
        var extend = {};
        extend[layui.cache.page] = layui.cache.page;
        layui.extend(extend);
        layui.use(layui.cache.page);
    }

    //手机设备的简单适配
    var treeMobile = $('.site-tree-mobile')
        , shadeMobile = $('.site-mobile-shade');

    treeMobile.on('click', function () {
        $('body').addClass('site-mobile');
    });

    shadeMobile.on('click', function () {
        $('body').removeClass('site-mobile');
    });

    //右下角按钮
    util.fixbar({
        bar1: '&#xe642;'
        , bgcolor: '#009688'
        , click: function (type) {
            if (type === 'bar1') {
                // 还是用弹出层 搞定发文章
                if (window.location.href.toString().indexOf("/jie/add") > 0) {
                    //console.log(window.location.href.toString());
                    layer.msg("你已经在编辑页面了");
                } else {
                    lucode.openWindowCheckLogin(lucode.cms + "/jie/add.html", ['95%', '90%']);
                }

            }
        }
    });

    // 文章列表
    function getPostList(extendParams,elem) {
        flow.load({
            //elem: '#stickList' //指定列表容器
            elem: elem
            ,isAuto: false
            , done: function (page, next) { //到达临界点（默认滚动触发），触发下一页
                var lis = [];
                //以jQuery的Ajax请求为例，请求下一页数据（注意：page是从2开始返回）
                // 文章列表载入
                lucode.lucodeGet(lucode.serverURL + "/cmsPost/get/list/"+page+"/5/" + extendParams,
                    null, null, function (data) {
                        //console.log(data);
                        layui.each(data.data.list, function (index, item) {
                            lis.push("<li>" +
                                "<a href=\"user/home.html#userId="+item.userInfoModel.userId+"\" class=\"fly-avatar\">\n" +
                                "<img src=\""+item.cmsPost.image+"\" alt=\"头像\">" +
                                "</a>" +
                                "<h2>" +
                                //"<a class=\"layui-badge\">分享</a>" +
                                "<a href=\"#\" onclick=\"lucode.openWindow('"+lucode.cms+"/jie/detail.html?postId="+item.cmsPost.id+"')\">"+item.cmsPost.title+"</a>"+
                                "</h2>" +
                                "<div class=\"fly-list-info\">" +
                                "<a href=\"user/home.html?userId="+item.userInfoModel.userId+"\" link>" +
                                "<cite>"+item.userInfoModel.nickname+"</cite>" +
                                "<i class=\"iconfont icon-renzheng\" title=\"认证信息：XXX\"></i>" +
                                "<i class=\"layui-badge fly-badge-vip\">SVIP</i>" +
                                "</a>" +
                                "<span>"+lucode.formatDate(item.cmsPost.gmtModify)+"</span>" +
                                //"<span class=\"fly-list-kiss layui-hide-xs\" title=\"众筹资金\"><i class=\"iconfont icon-kiss\"></i>60</span>" +
                                "<span class=\"layui-badge fly-badge-accept layui-hide-xs\">"+item.cmsPost.typeId+"</span>" +
                                "<span class=\"fly-list-nums\"><i class=\"iconfont \" title=\"人气\">&#xe60b;</i>"+item.cmsPost.readCount+"</span>" +
                                "</div>" +
                                " <div class=\"fly-list-badge\">\n" +
                                "<span class=\"layui-badge layui-bg-red\">众筹目标: "+item.cmsPost.cash+" 人民币</span>" +
                                "</div>" +
                                "</li>");
                        });
                        //执行下一页渲染，第二参数为：满足“加载更多”的条件，即后面仍有分页
                        //pages为Ajax返回的总页数，只有当前页小于总页数的情况下，才会继续出现加载更多
                        next(lis.join(''), page < data.data.totalPage);
                    });
            }
        });
    }


    // 页面加载完成后执行的任务
    $(document).ready(function () {
        var url = window.location.href;
        // 检查登陆情况
        lucode.getLoginInfo(function (usrInfo) {
            if (usrInfo == null) {
                var html = "<ul class=\"layui-nav fly-nav-user\">" +
                    "<li class=\"layui-nav-item\">" +
                    "    <a class=\"iconfont icon-touxiang layui-hide-xs\" onclick=\"lucode.openLoginWindow()\"></a>" +
                    "</li>" +
                    "<li class=\"layui-nav-item\">\n" +
                    "    <a href=\"#\" onclick=\"lucode.openLoginWindow('login.html')\" style=\"color: black;font-weight:800\">登入</a>\n" +
                    "</li>" +
                    "<li class=\"layui-nav-item\">\n" +
                    "    <a href=\"#\" onclick=\"lucode.openLoginWindow('register.html')\" style=\"color: black;font-weight:800\">注册</a>\n" +
                    "</li>" +
                    "</ul>";
                $("#userInfo").html(html);
            } else {
                var html = "<div onclick='lucode.openWindow(lucode.cms+\"/user/\");'><ul class=\"user layui-nav fly-nav-user\">" +
                    "  <li class=\"user layui-nav-item\">" +
                    "<a class=\"fly-nav-avatar\">" +
                    "<cite class=\"user layui-hide-xs\">" + usrInfo.nickname + "</cite>" +
                    "<i class=\"user iconfont icon-renzheng layui-hide-xs\" title=\"认证信息\"></i>" +
                    "<i class=\"user layui-badge fly-badge-vip layui-hide-xs\">VIP3</i>" +
                    "<img class=\"user\" src=\'" + usrInfo.avatar + "\'/>" +
                    "<span class=\"layui-nav-more\"></span></a>" +
                    "</li><span class=\"layui-nav-bar\" style=\"left: 0px; top: 56px; width: 0px; opacity: 0;\"></span></ul></div>";
                $("#userInfo").html(html);
            }
        });

        if (url.toString().indexOf("index") < 0) {
            return false;
        }

        // 先载入置顶文章
        getPostList("IS_STICK","#stickList");
        //根据 url 载入 相关类型的文章
        if (url != null && url.toString().indexOf("type") > 0) {
            //正则取出 参数
            var p = lucode.parseUrl(url);
            // 弹出层
            getPostList(p.type,"#allList");
        } else {
            // 默认按照最新的展示
            getPostList("all","#allList");
        }



        /**
         * 显示文章
         */
        if (url != null && url.toString().indexOf("post") > 0) {
            //正则取出 参数
            var postId = lucode.getStringByRegular(url);
            // 弹出层
            lucode.openWindow(lucode.cms + "/jie/detail.html?postId=" + postId);
        }

    });



    exports('fly', fly);
});

